﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using TCommon.Enum;
using ManageLiteAV;
using TCommon;
using TCommon.Entity;
using Newtonsoft.Json;
using TRTCMain.Properties;
using System.Threading.Tasks;
using TCommon.Util;

namespace TRTCMain.Controls
{
    public partial class UserItem : UserControl
    {
        private string userName;
        public static bool isHost = false;
        private string HostUserName = "";
        private string CurrentUser = "";
        private ITRTCCloud mTRTCCloud;
        private bool isHandOn = false;
        private bool isMute = false;//是否静音
        private bool isMicroOn = false;//是否上麦
        public delegate void ViewUserVideoHandler(string userName);
        public event ViewUserVideoHandler ViewUserVideoClicked;

        public delegate void FocuseUserHandler(string userName);
        public event FocuseUserHandler FocuseUserClicked;
        public static List<string> list = new List<string>();

        public delegate void RemoveUserHanlder(string userid);
        public event RemoveUserHanlder RemoveUserClicked;
        public bool IsOnScreen { get; set; }

        public UserItem(string username, ITRTCCloud mTRTCCloud, bool isHost1)
        {
            this.mTRTCCloud = mTRTCCloud;
            isHost = isHost1;
            this.userName = username;
            InitializeComponent();
            userNameLabel.Tag = username;
           // picCamera.Tag = username;
            picFocus.Tag = username;
            picLookvideo.Tag = username;
            if (TCommon.AppContext.isHost == false)
            {
                picFocus.Enabled = false;
                picFocus.Visible = false;
            }
            if (username == TCommon.AppContext.FocusedUser) {
                picFocus.Image = Resources.isFocus;
            }
            if (TRTC.VideoMainForm.isscene1 == "1" || TRTC.VideoMainForm.isscene1 == "2")
            {
                picLookvideo.Visible = false;
                picFocus.Visible = false;
            }

            picFocus.Click += PicFocus_Click;
            picLookvideo.Click += PicLookvideo_Click;
            // picCamera.Visible = false;
            // this.picCamera.MouseClick += UserItem_MouseClick;
            this.picHand.MouseClick += UserItem_MouseClick;
            this.picMicro.MouseClick += UserItem_MouseClick;
            this.picUser.MouseClick += UserItem_MouseClick;
            this.userNameLabel.MouseClick += UserItem_MouseClick;
            picCamera.MouseMove += new MouseEventHandler(UserItem_MouseMove);
            picCamera.MouseLeave += new EventHandler(UserItem_MouseLeave);
            picHand.MouseMove += new MouseEventHandler(UserItem_MouseMove);
            picHand.MouseLeave += new EventHandler(UserItem_MouseLeave);
            picMicro.MouseMove += new MouseEventHandler(UserItem_MouseMove);
            picMicro.MouseLeave += new EventHandler(UserItem_MouseLeave);
            picUser.MouseMove += new MouseEventHandler(UserItem_MouseMove);
            picUser.MouseLeave += new EventHandler(UserItem_MouseLeave);
            userNameLabel.MouseMove += new MouseEventHandler(UserItem_MouseMove);
            userNameLabel.MouseLeave += new EventHandler(UserItem_MouseLeave);
            picFocus.MouseMove += new MouseEventHandler(UserItem_MouseMove);
            picFocus.MouseLeave += new EventHandler(UserItem_MouseLeave);
            picLookvideo.MouseMove += new MouseEventHandler(UserItem_MouseMove);
            picLookvideo.MouseLeave += new EventHandler(UserItem_MouseLeave);
            
            string name = StringUtil.UserNameFromHex(username);
            string displayName = name;
            if (name.Length > 10) {
                displayName = name.Substring(0, 10) + "..";
            }
            this.userNameLabel.Text = displayName;
            ToolTip tip = new ToolTip();
            tip.SetToolTip(userNameLabel, name);
            if (TCommon.AppContext.startFromOldVersion) {
                picCamera.Visible = false;
                picHand.Visible = false;
                picFocus.Visible = false;
                picMicro.Visible = false;
                picLookvideo.Visible = false;
            }
        }

        public void SetFocuse(bool focuse) {
            if (focuse)
            {
                picFocus.Image = Resources.isFocus;
                if (!TCommon.AppContext.isHost)
                {
                    picFocus.Visible = true;
                }
            }
            else
            {
                picFocus.Image = Resources.noFocus;
                if (!TCommon.AppContext.isHost)
                {
                    picFocus.Visible = false;
                }
            }
        }

        private void PicLookvideo_Click(object sender, EventArgs e)
        {
            if (TCommon.AppContext.isSharingScreen)
                return;

            PictureBox pictureBox = sender as PictureBox;
            ViewUserVideoClicked?.Invoke(pictureBox.Tag.ToString());
        }
        //PictureBox pictureBoxOld;
        private void PicFocus_Click(object sender, EventArgs e)
        {
            if (TCommon.AppContext.isSharingScreen)
                return;

            PictureBox pictureBox = sender as PictureBox;
            if (Pic.pictureBoxOld == null)
            {
            }
            else if(pictureBox.Tag.ToString()!= TRTC.VideoMainForm.Focuse)
            {
                Pic.pictureBoxOld.Image = Resources.noFocus;
            }

            Pic.pictureBoxOld = pictureBox;
            if (TRTC.VideoMainForm.Focuse == pictureBox.Tag.ToString()) return;
            else
            {
                byte[] data;
                var action = new ActionEntity();
                string actionString = "";
                string inputMsg = "";
                string roomId = userName.Substring(1, userName.Length - 1);

                inputMsg = string.Format("{0}\"roomid\":{1},\"userid\":\"{2}\",\"cmd\":113{3}", "{", TRTC.VideoMainForm.roomId1, userName, "}");
                TRTC.VideoMainForm.fasongmessage(inputMsg);

                TRTC.VideoMainForm.Focuse = pictureBox.Tag.ToString();
                action.ActionId = HostAction.FocuseUser;    
                action.UserId = userName;
                actionString = JsonConvert.SerializeObject(action);
                data = Encoding.UTF8.GetBytes(actionString);
                var sucess = mTRTCCloud?.sendCustomCmdMsg(MessageId.HostAction, data, (uint)data.Length, true, true);
                FocuseUserClicked?.Invoke(pictureBox.Tag.ToString());
                pictureBox.Image = Resources.isFocus;
                Task.Factory.StartNew(() =>
                {
                    var manager = new ServiceManager();
                    manager.SetFocuseUser(TCommon.AppContext.LocalRoomId, userName);
                });

                
            }
          }
        public void SetIsHostUsed(bool isHost1, string HostUserName)
        {
            isHost = isHost1;
            this.HostUserName = HostUserName;
        }

        public void SetNameColor(Color color, bool isOnScreen) {
            userNameLabel.ForeColor = color;
            IsOnScreen = isOnScreen;
        }

        public void SetCurrentUser(string currentUser)
        {
            CurrentUser = currentUser;
        }

        public void SetHost()
        {
            string name = StringUtil.UserNameFromHex(userName);
            string displayName = name;
            if (name.Length > 6) {
                displayName = name.Substring(0, 6) + "..";
            }
            this.userNameLabel.Text = displayName + "-主持人";
            ToolTip tooltip = new ToolTip();
            tooltip.SetToolTip(userNameLabel, name + "-主持人");
            this.picUser.Image = Resources.host;
        }

        public bool IsHandOn()
        {
            return this.isHandOn;
        }

        public void SetVideoAvailable(bool available)
        {
            if (available && !TCommon.AppContext.startFromOldVersion)
            {
                this.picCamera.Image = Resources.cvon;
            }
            else
            {
                this.picCamera.Image = Resources.closesp;
            }
        }
        public void SetHandeRasied(bool raised)
        {
            this.picHand.Visible = raised;
            this.isHandOn = raised;
        }

        public void SetMicroOn(bool on) {
            isMicroOn = on;
        }

        public void UpdateUserName(string userId, string userName)
        {
            if (!string.IsNullOrEmpty(userName))
            {
                userNameLabel.Text = $"{userId}({userName})";
            }
            else
            {
                userNameLabel.Text = userId;
            }

            if (userId == HostUserName)
            {
                userNameLabel.Text = $"{userNameLabel.Text}-主持人";
            }
        }

        public void SetAudioAvailable(bool available)
        {
            if (available)
            {
                this.picMicro.Image = Resources.cmon;
            }
            else
            {
                this.picMicro.Image = Resources.cmoff;
            }
        }

        private void UserItem_MouseClick(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                ContextMenuStrip menu = new ContextMenuStrip();   //初始化menu
                menu.ItemClicked += Menu_ItemClicked;

                //if (CurrentUser == userName) {
                //    menu.Items.Add("修改参会名称");
                //}
                //if (isHost && TRTC.VideoMainForm.isscene1 == "")
                //{
                //    menu.Items.Add("设为焦点");
                //}
                if (TCommon.AppContext.isHost && userName != TCommon.AppContext.HostId)
                {
                    if (TRTC.VideoMainForm.isscene1 == "2")
                    {
                        if (isMicroOn == false)
                        {
                            if (VideoContainer.normalScreenUsers.Count < 4)
                            {
                                menu.Items.Add("上麦");
                            }
                        }
                        else
                        {
                            menu.Items.Add("下麦");
                        }

                    }

                    if (!isMute)
                    {
                        menu.Items.Add("静音");
                    }
                    else if (isMute)
                    {
                        menu.Items.Add("取消静音");
                    }

                    //if (isVideoOn())
                    //{
                    //    menu.Items.Add("关闭视频");
                    //}
                    //else {
                    //    menu.Items.Add("打开视频");
                    //}

                    if (IsHandOn())
                    {
                        menu.Items.Add("放下举手");
                    }

                    menu.Items.Add("移出会议");
                }
                menu.Show(this, new Point(e.X, e.Y));   //在点(e.X, e.Y)处显示menu
            }
        }
        
        public bool isclivk = false;
        private void Menu_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {
            string inputMsg = "";
            byte[] data;
            var action = new ActionEntity();
            string actionString = "";
            var actionName = e.ClickedItem.Text;
            string newusername = userName.Substring(1, userName.Length - 1);
            switch (actionName)
            {
                case "静音":
                    inputMsg = string.Format("{0}\"roomid\":{1},\"userid\":\"{2}\",\"cmd\":111{3}", "{", TRTC.VideoMainForm.roomId1, userName, "}");
                    TRTC.VideoMainForm.fasongmessage(inputMsg);
                    this.isMute = true;
                    action.ActionId = HostAction.MuteUser;
                    action.UserId = userName;
                    actionString = JsonConvert.SerializeObject(action);
                    data = Encoding.UTF8.GetBytes(actionString);
                    mTRTCCloud?.sendCustomCmdMsg(MessageId.HostAction, data, (uint)data.Length, true, true);
                    break;
                case "取消静音":
                    string inputMsg1 = string.Format("{0}\"roomid\":{1},\"userid\":\"{2}\",\"cmd\":112{3}", "{", TRTC.VideoMainForm.roomId1, userName, "}");
                    TRTC.VideoMainForm.fasongmessage(inputMsg1);
                    this.isMute = false;
                    action.ActionId = HostAction.UnMuteUser;
                    action.UserId = userName;
                    actionString = JsonConvert.SerializeObject(action);
                    data = Encoding.UTF8.GetBytes(actionString);
                    mTRTCCloud?.sendCustomCmdMsg(MessageId.HostAction, data, (uint)data.Length, true, true);
                    break;
                case "放下举手":
                    inputMsg = string.Format("{0}\"roomid\":{1},\"userid\":\"{2}\",\"cmd\":3{3}", "{", TRTC.VideoMainForm.roomId1, userName, "}");
                    TRTC.VideoMainForm.fasongmessage(inputMsg);
                    action.ActionId = HostAction.DownUserHand;
                    action.UserId = userName;
                    actionString = JsonConvert.SerializeObject(action);
                    data = Encoding.UTF8.GetBytes(actionString);
                    mTRTCCloud?.sendCustomCmdMsg(MessageId.HostAction, data, (uint)data.Length, true, true);
                    break;
                case "移出会议":
                    RemoveUserClicked?.Invoke(userName);
                    inputMsg = string.Format("{0}\"roomid\":{1},\"userid\":\"{2}\",\"cmd\":110{3}", "{", TRTC.VideoMainForm.roomId1, userName, "}");
                    TRTC.VideoMainForm.fasongmessage(inputMsg);
                    action.ActionId = HostAction.RemoveUser;
                    action.UserId = userName;
                    actionString = JsonConvert.SerializeObject(action);
                    data = Encoding.UTF8.GetBytes(actionString);
                    mTRTCCloud?.sendCustomCmdMsg(MessageId.HostAction, data, (uint)data.Length, true, true);
                    break;
                case "查看视频":
                    ViewUserVideoClicked?.Invoke(userName);
                    break;
                case "设为焦点":
                    inputMsg = string.Format("{0}\"roomid\":{1},\"userid\":\"{2}\",\"cmd\":113{3}", "{", TRTC.VideoMainForm.roomId1, userName, "}");
                    TRTC.VideoMainForm.fasongmessage(inputMsg);
                    TRTC.VideoMainForm.Focuse = userName;
                    FocuseUserClicked?.Invoke(userName);
                    action.ActionId = HostAction.FocuseUser;
                    action.UserId = userName;
                    actionString = JsonConvert.SerializeObject(action);
                    data = Encoding.UTF8.GetBytes(actionString);
                    mTRTCCloud?.sendCustomCmdMsg(MessageId.HostAction, data, (uint)data.Length, true, true);
                    break;
                case "上麦":
                    inputMsg = string.Format("{0}\"roomid\":{1},\"cmd\":{2},\"userid\":\"{3}\"{4}", "{", TRTC.VideoMainForm.roomId1, 126, userName, "}");
                    TRTC.VideoMainForm.fasongmessage(inputMsg);
                    TRTC.VideoMainForm.topupmai = true;
                    this.isMicroOn = true;
                    break;
                case "下麦":
                    inputMsg = string.Format("{0}\"roomid\":{1},\"cmd\":{2},\"userid\":\"{3}\"{4}", "{", TRTC.VideoMainForm.roomId1, 125, userName, "}");
                    TRTC.VideoMainForm.fasongmessage(inputMsg);
                    TRTC.VideoMainForm.topupmai = false;
                    this.isMicroOn = false;
                    break;
                    //case "修改参会名称":
                    //    var form = new InputUserNameForm(mTRTCCloud, userName);
                    //    form.NameChanged += Form_NameChanged;
                    //    form.ShowDialog();
                    //    break;
                    //case "打开视频":
                    //    inputMsg = string.Format("{0}\"roomid\":{1},\"userid\":{2},\"cmd\":116{3}", "{", TRTC.VideoMainForm.roomId1, userName, "}");
                    //    fasongmessage(inputMsg);
                    //    action.ActionId = HostAction.OpenUserVideo;
                    //    action.UserId = userName;
                    //    actionString = JsonConvert.SerializeObject(action);
                    //    data = Encoding.UTF8.GetBytes(actionString);
                    //    mTRTCCloud?.sendCustomCmdMsg(MessageId.HostAction, data, (uint)data.Length, true, true);
                    //    break;
                    //case "关闭视频":
                    //    inputMsg = string.Format("{0}\"roomid\":{1},\"userid\":{2},\"cmd\":115{3}", "{", TRTC.VideoMainForm.roomId1, userName, "}");
                    //    fasongmessage(inputMsg);
                    //    action.ActionId = HostAction.CloseUserVideo;
                    //    action.UserId = userName;
                    //    actionString = JsonConvert.SerializeObject(action);
                    //    data = Encoding.UTF8.GetBytes(actionString);
                    //    mTRTCCloud?.sendCustomCmdMsg(MessageId.HostAction, data, (uint)data.Length, true, true);
                    //    break;
            }
        }

        private void Form_NameChanged(string userName)
        {
            if (!string.IsNullOrEmpty(userName))
            {
                userNameLabel.Text = $"{this.userName}({userName})";
            }
            else
            {
                userNameLabel.Text = this.userName;
            }

            if (isHost)
            {
                userNameLabel.Text = $"{userNameLabel.Text}-主持人";
            }
        }

        private void UserItem_Paint(object sender, PaintEventArgs e)
        {
            ControlPaint.DrawBorder(e.Graphics, ClientRectangle, Color.LightGray, ButtonBorderStyle.Solid);
        }

        private bool isMuteAudio()
        {
            return picMicro.Image == Resources.cmoff;
        }

        private bool isVideoOn()
        {
            return picCamera.Image == Resources.cvon;
        }

        private void UserItem_MouseMove(object sender, MouseEventArgs e)
        {
                this.BackColor = Color.FromArgb(110, 70, 72);
              //  userNameLabel.ForeColor = Color.White;
        }

        private void UserItem_MouseLeave(object sender, EventArgs e)
        {
            this.BackColor = Color.White;
          //  userNameLabel.ForeColor = Color.Black;
        }
    }
    public class Pic
    {
      public static PictureBox pictureBoxOld;
    }
}
